package cn.liccshop.sys.utils;

import cn.liccshop.sys.constants.Constants;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.UUID;

/**
 * @author LiCC
 * @program LiCCShop
 * @description AES对称加密密码
 * @since 2019-04-06-22:49
 */
public class AESUtil {
    /**
     * 加密算法名字
     */
    public static final String KEY_ALGORITHM = "AES";
    /**
     * 加密算法的模式
     */
    public static final String KEY_ALGORITHM_MODE = "AES/CBC/PKCS5Padding";

    /**
     * AES对称加密 key需要16位
     * @param data
     * @return
     */
    public static String encrypt(String data) {
        try {
            /** 根据字节数组生成AES密钥,Constants.AES_KEY：加密的Key,KEY_ALGORITHM：加密名称**/
            SecretKeySpec spec = new SecretKeySpec(Constants.AES_KEY.getBytes("UTF-8"),KEY_ALGORITHM);
            /** 根据指定算法AES自成密码器 KEY_ALGORITHM_MODE：加密方式**/
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_MODE);
            /** 始化密码器，第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作，第二个参数为使用的KEY **/
            cipher.init(Cipher.ENCRYPT_MODE , spec,new IvParameterSpec(new byte[cipher.getBlockSize()]));
            /** 根据密码器的初始化方式--加密：将数据加密 **/
            byte[] bs = cipher.doFinal(data.getBytes("UTF-8"));
            /** Base64处理字节 **/
            return Base64Util.encode(bs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }
    /**
     * AES对称解密 key需要16位
     * @param data
     * @return
     */
    public static String decrypt(String data) {
        try {
            SecretKeySpec spec = new SecretKeySpec(Constants.AES_KEY.getBytes("UTF-8"), KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_MODE);
            cipher.init(Cipher.DECRYPT_MODE , spec , new IvParameterSpec(new byte[cipher.getBlockSize()]));
            byte[] originBytes = Base64Util.decode(data);
            byte[] result = cipher.doFinal(originBytes);
            return new String(result,"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }

    public static void main(String[] args) {
//        String encrypt = encrypt("dsgfsdasfsadfasfsddfg");
//        System.out.println(encrypt);
//        String decrypt = decrypt(encrypt);
//        System.out.println(decrypt);
        for(int i = 0; i < 100; i++)
        {
            System.out.println(UUID.randomUUID().toString().replaceAll("-", ""));
        }
    }
}
